import { http } from '@/utils/request'
import type { AssistantMessage, ChatMessage, QuickAction, ApiResponse } from '@/types'
import Cookies from 'js-cookie'

// 流式消息响应类型
export interface StreamResponse {
  type: 'start' | 'chunk' | 'end' | 'error';
  message: string;
}

// 发送消息 - 流式响应
export const sendMessageStream = (
  data: { message: string; type?: 'text' | 'voice' },
  onChunk: (chunk: StreamResponse) => void,
  onComplete: (fullResponse: string) => void,
  onError: (error: string) => void
): (() => void) => {
  const controller = new AbortController();
  
  fetch('/api/client/ai-assistants/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${Cookies.get('token') || ''}`
    },
    body: JSON.stringify(data),
    signal: controller.signal
  })
  .then(response => {
    if (!response.ok) {
      // 处理认证错误
      if (response.status === 401) {
        throw new Error('未授权，请重新登录');
      }
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    let fullResponse = '';
    let buffer = '';
    
    if (reader) {
      const readChunk = () => {
        reader.read().then(async ({ done, value }) => {
          if (done) {
            onComplete(fullResponse);
            return;
          }
          
          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;
          
          // 按行分割并处理
          const lines = buffer.split('\n');
          buffer = lines.pop() || ''; // 保留不完整的行
          
          for (const line of lines) {
            await new Promise(resolve => setTimeout(resolve, 5));
            if (line.trim() && line.startsWith('data: ')) {
              try {
                // 处理可能的转义问题
                let jsonStr = line.slice(6);
                
                // 如果JSON字符串不完整，跳过这次解析
                if (!jsonStr.trim()) continue;
                
                // 尝试解析JSON
                const data = JSON.parse(jsonStr);
                // 立即处理每个chunk
                if (data.type === 'chunk') {
                  fullResponse += data.message;
                  // 立即调用回调，确保实时显示
                  onChunk(data);
                } else if (data.type === 'error') {
                  onError(data.message);
                  return;
                } else if (data.type === 'end') {
                  // 处理结束标记
                  onComplete(fullResponse);
                  return;
                } else {
                  // 处理其他类型（start等）
                  onChunk(data);
                }
              } catch (e) {
                // 记录解析错误，但继续处理
                console.warn('解析流式数据失败:', e, '原始数据:', line);
                
                // 尝试处理不完整的JSON
                const jsonStr = line.slice(6);
                if (jsonStr.includes('"type"') && jsonStr.includes('"message"')) {
                  // 可能是JSON格式正确但内容有问题，尝试修复
                  try {
                    // 移除可能的换行符和特殊字符
                    const cleanedStr = jsonStr.replace(/\n/g, '\\n').replace(/\r/g, '\\r');
                    const data = JSON.parse(cleanedStr);
                    if (data.type === 'chunk') {
                      fullResponse += data.message;
                      onChunk(data);
                    }
                  } catch (e2) {
                    // 如果还是失败，就跳过这个chunk
                    console.warn('修复JSON解析也失败:', e2);
                  }
                }
              }
            }
          }
          
          readChunk();
        }).catch(error => {
          onError(error.message);
        });
      };
      
      readChunk();
    }
  })
  .catch(error => {
    onError(error.message);
  });
  
  // 返回取消函数
  return () => controller.abort();
};

// 发送消息 - 兼容旧版本
export const sendMessage = (data: {
  message: string;
  type?: 'text' | 'voice';
}): Promise<ApiResponse<{
  chatId: number;
  response: string;
}>> => {
  return http.post('/client/ai-assistants/chat', data)
}

// 获取聊天历史
export const getChatHistory = (params?: {
  page?: number;
  pageSize?: number;
}): Promise<ApiResponse<{
  items: AssistantMessage[];
  pagination: {
    total: number;
    page: number;
    pageSize: number;
    totalPages: number;
  };
}>> => {
  return http.get('/client/ai-assistants/chat-history', { params })
}

// 获取快捷操作
export const getQuickActions = (): Promise<ApiResponse<QuickAction[]>> => {
  return http.get('/client/ai-assistants/quick-actions')
}

// 语音转文字
export const voiceToText = (audioFile: File): Promise<ApiResponse<{
  text: string;
}>> => {
  const formData = new FormData()
  formData.append('audio', audioFile)
  
  return http.post('/client/ai-assistants/voice-to-text', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 生成图片
export const generateImage = (prompt: string): Promise<ApiResponse<{
  imageUrl: string;
}>> => {
  return http.post('/client/ai-assistants/generate-image', { prompt })
}

// 提问 - 流式响应
export const askQuestionStream = (
  question: string,
  onChunk: (chunk: StreamResponse) => void,
  onComplete: (fullResponse: string) => void,
  onError: (error: string) => void
): (() => void) => {
  const controller = new AbortController();
  
  fetch('/api/client/ai-assistants/ask', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${Cookies.get('token') || ''}`
    },
    body: JSON.stringify({ question }),
    signal: controller.signal
  })
  .then(response => {
    if (!response.ok) {
      // 处理认证错误
      if (response.status === 401) {
        throw new Error('未授权，请重新登录');
      }
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    let fullResponse = '';
    let buffer = '';
    
    if (reader) {
      const readChunk = () => {
        reader.read().then(({ done, value }) => {
          if (done) {
            onComplete(fullResponse);
            return;
          }
          
          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;
          
          // 按行分割并处理
          const lines = buffer.split('\n');
          buffer = lines.pop() || ''; // 保留不完整的行
          
          for (const line of lines) {
            if (line.trim() && line.startsWith('data: ')) {
              try {
                // 处理可能的转义问题
                let jsonStr = line.slice(6);
                
                // 如果JSON字符串不完整，跳过这次解析
                if (!jsonStr.trim()) continue;
                
                // 尝试解析JSON
                const data = JSON.parse(jsonStr);
                console.log('解析的流式数据:', data); // 调试信息
                
                // 立即处理每个chunk
                if (data.type === 'chunk') {
                  fullResponse += data.message;
                  // 立即调用回调，确保实时显示
                  onChunk(data);
                } else if (data.type === 'error') {
                  onError(data.message);
                  return;
                } else if (data.type === 'end') {
                  // 处理结束标记
                  onComplete(fullResponse);
                  return;
                } else {
                  // 处理其他类型（start等）
                  onChunk(data);
                }
              } catch (e) {
                // 记录解析错误，但继续处理
                console.warn('解析流式数据失败:', e, '原始数据:', line);
                
                // 尝试处理不完整的JSON
                const jsonStr = line.slice(6);
                if (jsonStr.includes('"type"') && jsonStr.includes('"message"')) {
                  // 可能是JSON格式正确但内容有问题，尝试修复
                  try {
                    // 移除可能的换行符和特殊字符
                    const cleanedStr = jsonStr.replace(/\n/g, '\\n').replace(/\r/g, '\\r');
                    const data = JSON.parse(cleanedStr);
                    if (data.type === 'chunk') {
                      fullResponse += data.message;
                      onChunk(data);
                    }
                  } catch (e2) {
                    // 如果还是失败，就跳过这个chunk
                    console.warn('修复JSON解析也失败:', e2);
                  }
                }
              }
            }
          }
          
          readChunk();
        }).catch(error => {
          onError(error.message);
        });
      };
      
      readChunk();
    }
  })
  .catch(error => {
    onError(error.message);
  });
  
  // 返回取消函数
  return () => controller.abort();
};

// 提问 - 兼容旧版本
export const askQuestion = (question: string): Promise<ApiResponse<{
  chatId: number;
  response: string;
}>> => {
  return http.post('/client/ai-assistants/ask', { question })
} 